package com.yhq.basic.jvm.classload.custom;

import lombok.SneakyThrows;
import sun.misc.Resource;
import sun.misc.URLClassPath;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.util.jar.Manifest;

/**
 * @author hqyin
 * @date 2024/7/31 11:40 AM
 */
public class MyClassLoader1 extends ClassLoader {

    private final URLClassPath ucp;

    public MyClassLoader1(URL[] urls) {
        ucp = new URLClassPath(urls);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return super.defineClass(name, b, 0, b.length);
    }

    @SneakyThrows
    private byte[] loadClassData(String name) {
        //根据全路径名加载类
        String path = name.replace('.', '/').concat(".class");
        Resource res = ucp.getResource(path, false);

        //判断url是否有包名
        int i = name.lastIndexOf('.');
        if (i != -1) {
            String pkgname = name.substring(0, i);
            // Check if package already loaded.
            definePackage(pkgname, null, null, null, null, null, null, null);
        }

        //读取数据
        java.nio.ByteBuffer bb = res.getByteBuffer();
        if(bb!= null) {
            int len = bb.remaining();
            byte[] tb = new byte[len];
            bb.get(tb);
            return tb;
        }
        return  res.getBytes();

    }
}
